package gamagora.game.world.maps
{
	import gamagora.game.entity.OSEntity;
	
	import org.flixel.FlxSprite;

	public class OSMap extends OSEntity
	{
		public static const WIDTH:Number = 960;
		public static const HEIGHT:Number = 1080;
		
		//Only for rendering
		private var _grounds:Vector.<OSEntity>;
		private var _backgrounds:Vector.<OSEntity>;
		private var _foregrounds:Vector.<OSEntity>;
		private var _specialBackground:FlxSprite;
		
		private var _nbGrounds:uint;
		private var _nbBackgrounds:uint;
		private var _nbForegrounds:uint;
		
		public function OSMap(specialBackground:Class = null)
		{
			super(NOTHING);
			_hide = true;
			if(specialBackground != null)
			{
				_specialBackground = new FlxSprite(0, 0, specialBackground);
			}
			
			_grounds = new Vector.<OSEntity>();
			_backgrounds = new Vector.<OSEntity>();
			_foregrounds = new Vector.<OSEntity>();
			
			_nbGrounds = 0;
			_nbBackgrounds = 0;
			_nbForegrounds = 0;
		}
		
		//Override
		
		public override function add(entity:OSEntity):void
		{
			super.add(entity);
			_grounds.push(entity);
			_nbGrounds++;
		}
		
		public override function draw():void
		{
			if(visible)
			{
				if(_specialBackground != null)
				{
					_specialBackground.draw();
				}
				
				for(var i:uint=0;i<_nbGrounds;i++)
				{
					_grounds[i].draw();
				}
			}
		}
		
		public override function setStartX(decalX:Number):void
		{
			super.setStartX(decalX);
			if(_specialBackground != null)
			{
				_specialBackground.x += decalX;
			}
		}
		
		public override function destroy():void
		{
			super.destroy();
			if(_specialBackground != null)
			{
				_specialBackground.destroy();
			}
		}
		
		//Utils
		
		public function hasSpecialBackground():Boolean
		{
			return _specialBackground != null;
		}
		
		public function addBackground(entity:OSEntity):void
		{
			super.add(entity);
			_backgrounds.push(entity);
			_nbBackgrounds++;
		}
		
		public function addForeground(entity:OSEntity):void
		{
			super.add(entity);
			_foregrounds.push(entity);
			_nbForegrounds++;
		}
		
		public function drawBackgrounds():void
		{
			for(var i:uint=0;i<_nbBackgrounds;i++)
			{
				_backgrounds[i].draw();
			}
		}
		
		public function drawForegrounds():void
		{
			for(var i:uint=0;i<_nbForegrounds;i++)
			{
				_foregrounds[i].draw();
			}
		}
		
		public function leftClosed(playerX:Number, limit:uint = 50):Boolean
		{
			return playerX >= x - limit;
		}
		
		public function rightClosed(playerX:Number, limit:uint = 50):Boolean
		{
			return playerX <= x + WIDTH + limit;
		}
		
		public function inside(playerX:Number):Boolean
		{
			return playerX >= x && playerX <= x + WIDTH;
		}
	}
}
